import store from "../store";
import history from "./route/history";

/**
 *
 * @param messageEntity 包含了 url ,type(方式),data(数据)
 * @returns {Promise<any | never>}
 */
export const fetchUtils = (messageEntity) => {

    const realUrl = messageEntity.url;

    const accountToken = store.getState().get("accountReducer").get("accountToken");

    const option = {
        method: messageEntity.method,
    };

    if (accountToken) {
        const headers = new Headers();
        console.log("请求携带token");
        headers.set("AccountToken", accountToken);// 让每个请求携带token

        option.headers = headers;
    } else {
        console.log("请求未携带token");
    }

    if (messageEntity.data) {
        option.body = JSON.stringify(messageEntity.data);
    }

    return fetch(realUrl, option)
        .then(res => res.json())
        .then(
            (response) => {

                console.log("收到的 数值 ");
                console.log(response);

                const statusCode = response.status;
                if (statusCode === 4000 || statusCode === 4001) {

                    console.log("收到状态码 4000");
                    history.replace("/login");
                } else if (statusCode === 4003) {

                    return response
                } else {
                    if (!response.resultStatus) {


                    }
                }
                return response;

            }, (error) => {
                console.log('fetch出现错误');
            }
        )
};